package com.iweb.service.impl;

import com.iweb.dao.UserDao;
import com.iweb.dao.impl.UserDaoImpl;

import com.iweb.entity.User;
import com.iweb.service.UserService;

import com.iweb.util.SecurityUtils;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();



    @Override
    public List<User> findList() throws Exception{
        return this.userDao.selectList();
    }

    @Override
    public User findByLoginName(String loginName) throws Exception {
        return this.userDao.selectUserByLoginName(loginName);
    }


    @Override
    public User findById(Integer id) throws Exception {
        return this.userDao.selectUserById(id);
    }

    /**
     * 验证用户登录
     *
     * @param loginName
     * @param password
     * @return null-用户名或密码有误
     * @throws Exception
     */
    @Override
    public User validateUser(String loginName, String password) throws Exception {
        // 根据用户名查询用户信息
        User user = this.findByLoginName(loginName);
        if (user == null) {
            return null;
        }
        // 比较当前用户输入的密码，跟数据库中保存的密码，是否一致
        if (user.getPassword().equals(SecurityUtils.md5Hex(password))) {
            return user;
        }
        return null;
    }

    @Override
    public boolean remove(Integer id) throws Exception {
        int result= this.userDao.delete(id);
        return result>0;
    }

    @Override
    public void add(User user) throws Exception {
        //设置初始密码,假设初始密码保存在配置文件里
        user.setPassword(SecurityUtils.md5Hex("123456"));
        this.userDao.insert(user);
    }


    @Override
    public boolean modify(User user) throws Exception {
        return this.userDao.update(user)>0;
    }



}
